package com.ganlucode.sipmock.sip.request.impl;

import com.ganlucode.sipmock.config.SipServerProperties;
import com.ganlucode.sipmock.gb28181.auth.DigestServerAuthenticationHelper;
import com.ganlucode.sipmock.gb28181.dto.Device;
import com.ganlucode.sipmock.gb28181.dto.Host;
import com.ganlucode.sipmock.service.IDeviceService;
import com.ganlucode.sipmock.sip.handler.RegisterHandler;
import com.ganlucode.sipmock.sip.request.ISipRequestProcessor;
import com.ganlucode.sipmock.utils.SipHelper;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.header.Expires;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.sip.RequestEvent;
import javax.sip.header.*;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.util.Calendar;
import java.util.Locale;

/**
 * @author GanLu
 */
@Slf4j
@Service("registerRequestProcessor")
public class RegisterRequestProcessor implements ISipRequestProcessor {

	@Autowired
	private RegisterHandler registerHandler;
	
	@Autowired
	private IDeviceService deviceService;
	

    @Autowired
    private SipServerProperties sipServerProperties;

    @Autowired
    private SipHelper sipHelper;

    @Autowired
    private HeaderFactory headerFactory;

    @Autowired
    private MessageFactory messageFactory;

	@Autowired
	private DigestServerAuthenticationHelper digestServerAuthenticationHelper;

	/***
	 * 收到注册请求 处理
	 *
	 * @param evt 请求消息
	 */ 
	@Override
	public void process(RequestEvent evt) throws Exception {
		log.debug("收到注册请求，开始处理");
		Request request = evt.getRequest();

		Response response = null;
		boolean passwordCorrect = false;
		// 注册标志  0：未携带授权头或者密码错误  1：注册成功   2：注销成功
		int registerFlag = 0;
		Device device = null;
		AuthorizationHeader authorhead = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
		// 校验密码是否正确
		if (authorhead != null) {
			passwordCorrect = digestServerAuthenticationHelper.doAuthenticatePlainTextPassword(request,
					sipServerProperties.getSipPassword());
		}

		// 未携带授权头或者密码错误 回复401
		if (authorhead == null || !passwordCorrect) {

			if (authorhead == null) {
				log.info("未携带授权头 回复401");
			} else {
				log.info("密码错误 回复401");
			}
			response = messageFactory.createResponse(Response.UNAUTHORIZED, request);
			digestServerAuthenticationHelper.generateChallenge(headerFactory, response, sipServerProperties.getSipDomain());
		}
		// 携带授权头并且密码正确
		else if (passwordCorrect) {
			response = messageFactory.createResponse(Response.OK, request);
			// 添加date头
			response.addHeader(headerFactory.createDateHeader(Calendar.getInstance(Locale.ENGLISH)));
			ExpiresHeader expiresHeader = (ExpiresHeader) request.getHeader(Expires.NAME);
			// 添加Contact头
			response.addHeader(request.getHeader(ContactHeader.NAME));
			// 添加Expires头
			response.addHeader(request.getExpires());

			// 1.获取到通信地址等信息，保存到Redis
			FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
			ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
			String received = viaHeader.getReceived();
			int rPort = viaHeader.getRPort();
			// 本地模拟设备 received 为空 rPort 为 -1
			// 解析本地地址替代
			if (StringUtils.isEmpty(received) || rPort == -1) {
				received = viaHeader.getHost();
				rPort = viaHeader.getPort();
			}
			//
			Host host = new Host();
			host.setIp(received);
			host.setPort(rPort);
			host.setAddress(received.concat(":").concat(String.valueOf(rPort)));
			AddressImpl address = (AddressImpl) fromHeader.getAddress();
			SipUri uri = (SipUri) address.getURI();
			String deviceId = uri.getUser();
			device = new Device();
			device.setDeviceId(deviceId);
			device.setHost(host);
			// 注销成功
			if (expiresHeader != null && expiresHeader.getExpires() == 0) {
				registerFlag = 2;
			}
			// 注册成功
			else {
				registerFlag = 1;
				ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
				device.setTransport(sipHelper.getTransport());
			}
		}
		sipHelper.createServerTransaction(evt).sendResponse(response);
		// 注册成功
		// 保存到redis
		// 下发catelog查询目录
//		if (registerFlag == 1 && device != null) {
//			log.info("注册成功! deviceId:" + device.getDeviceId());
//			registerHandler.onRegister(device);
//		} else if (registerFlag == 2) {
//			log.info("注销成功! deviceId:" + device.getDeviceId());
//		}
	}

}
